import React, { Component } from 'react'
import { Card, Form, Input, Row, Col, Button, DatePicker, TimePicker, Select, message } from 'antd';

import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import ScrollSelect from '@/components/ScrollSelect';

import router from 'umi/router';
import { connect } from 'dva';
import api from '@/api';
import moment from 'moment'

const FormItem = Form.Item
const { Option } = Select;

@connect(({ base }) => ({ cargoTypes: base.cargoTypes, }))
@Form.create()
class AirService extends Component {
  state = {
    mode: 'add',
    service: {}
  }
  week = [
    {
      key: 1,
      label: '1',
    },
    {
      key: 2,
      label: '2',
    },
    {
      key: 3,
      label: '3',
    },
    {
      key: 4,
      label: '4',
    },
    {
      key: 5,
      label: '5',
    },
    {
      key: 6,
      label: '6',
    },
    {
      key: 7,
      label: '7',
    },
  ];
  componentDidMount() {
    const { dispatch } = this.props;
    this.queryService()
    dispatch({ type: 'base/fetchCargoTypes' });
  }
  queryService = () => {
    const { location, dispatch } = this.props;
    dispatch({
      type: 'product/queryFlightById',
      payload: {
        pathParams: {
          id: location.query.serviceId
        }
      }
    }).then(({ errorCode, data }) => {
      if (errorCode === 0) {
        this.setState({ service: data })
      }
    })
  }
  handleSubmit = () => {
    const { dispatch, form: { validateFields }, location } = this.props;
    const { service } = this.state;
    let productType = location.pathname.split('/')[2], id
    switch (productType) {
      case 'today':
        id = 10000
        break;
      case 'tomorrow':
        id = 10001
        break;
      case 'time':
        id = 10002
        break
      default:
        id = 10000
    }
    validateFields((err, value) => {
      if (err) return
      // todo 修改数据提交的方式 避免数据没有提交
      let data = {
        "productId": id,
        "phaseId": location.query.phaseId,
        "nodeId": location.query.nodeId,
        "typeCode": location.query.serviceType,
        "typeCodeSub": "AIR",
        id: service.id,
        serviceId: service.serviceId,
        ...value,
        periodList: value.week,
        startPlace: value.start.key,
        endPlace: value.end.key,
        supplierId: value.supplierId.key
      }
      if (value.startTime) {
        data.startTime = moment(value.startTime).format('HH:mm')
      }
      if (value.arriveTime) {
        data.arriveTime = moment(value.arriveTime).format('HH:mm')
      }
      if (value.flightDate) {
        data.flightDate = moment(value.flightDate).format('YYYY-MM-DD')
      }
      if (value.effectStartDate) {
        data.effectStartDate = moment(value.effectStartDate).format('YYYY-MM-DD 00:00:00')
      }
      if (value.effectEndDate) {
        data.effectEndDate = moment(value.effectEndDate).format('YYYY-MM-DD 00:00:00')
      }
      if (value.operateSupplier) {
        data.operateSupplier = value.operateSupplier.key
      }
      delete data.start
      delete data.end
      delete data.week
      dispatch({
        type: 'product/putAirFlight',
        payload: {
          data,
          pathParams: {
            id: location.query.serviceId
          }
        }
      }).then(({ errorCode, data }) => {
        if (errorCode === 0) {
          message.success('干线编辑成功')
          this.handleCancel()
        }
      })
    })

  }
  handleCancel = () => {
    const { location } = this.props;
    router.push(location.query.backRoute)
  }
  checkCode = (rule, value, callback) => {
    if ('' === value) {
      return callback('请输入航班号')
    }
    if (!/^[A-Z0-9]{5,6}$/i.test(value)) {
      return callback('航班号格式不正确');
    }
    return callback()
  }
  queryAirports = params => {
    return api.base.queryAirport({
      queryParams: params,
    });
  };
  querySuppliers = params => {
    return api.supplier.shortQuery({
      queryParams: params,
    });
  };
  disableStartDate = (current) => {
    const { form: { getFieldValue } } = this.props;
    let time = getFieldValue('effectEndDate')
    if (!time) return false
    return current && current > moment(time).endOf('day');
  }
  disableEndDate = (current) => {
    const { form: { getFieldValue } } = this.props;
    let time = getFieldValue('effectStartDate')
    if (!time) return false
    return current && current < moment(time).endOf('day');
  }
  range = (start, end) => {
    const result = [];
    for (let i = start; i < end; i++) {
      result.push(i);
    }
    return result;
  }
  disableStartHour = () => {
    const { form: { getFieldValue } } = this.props;
    let time = getFieldValue('arriveTime')
    if (!time) return []
    return this.range(+moment(time).format('HH') + 1, 24)
  }
  disableArriveHour = () => {
    const { form: { getFieldValue } } = this.props;
    let time = getFieldValue('startTime')
    if (!time) return []
    return this.range(0, +moment(time).format('HH'))
  }
  disableStartMinute = (hour) => {
    const { form: { getFieldValue } } = this.props;
    let time = getFieldValue('arriveTime')
    if (time === undefined) {
      return []
    }
    let arriveHour = moment(time).format('HH')
    if (hour < arriveHour) {
      return []
    }
    return this.range(+moment(time).format('mm'), 59)
  }
  disableArriveMinute = (hour) => {
    const { form: { getFieldValue } } = this.props;
    let time = getFieldValue('startTime')
    if (time === undefined) {
      return []
    }
    let startHour = moment(time).format('HH')
    let startMinute = moment(time).format('mm')
    if (hour > startHour) {
      return []
    }
    return this.range(0, +startMinute + 1)
  }
  render() {
    const { location, form: { getFieldDecorator }, cargoTypes } = this.props;
    const { service } = this.state;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 18 },
      },
    };
    let isTime = location.pathname.includes('time')
    return (
      <PageHeaderWrapper title='空运' backRoute={location.query.backRoute}>
        <Card bordered={false}>
          <Row>
            <Col span={16}>
              <FormItem label="始发机场" {...formItemLayout}>
                {getFieldDecorator('start', {
                  rules: [
                    { required: true, message: '请选择始发机场' },
                  ],
                  initialValue: {
                    key: service.startPlace,
                    label: `${service.startPlaceName}(${service.startPlace})`
                  }
                })(
                  <ScrollSelect
                    allowClear
                    disabled={true}
                    search={this.queryAirports}
                    optionKey="code"
                    style={{ width: 300 }}
                  />
                )}
              </FormItem>
              <FormItem label="到达机场" {...formItemLayout}>
                {getFieldDecorator('end', {
                  rules: [
                    { required: true, message: '请选择到达机场' },
                  ],
                  initialValue: {
                    key: service.endPlace,
                    label: `${service.endPlaceName}(${service.endPlace})`
                  }
                })(
                  <ScrollSelect
                    allowClear
                    disabled={true}
                    search={this.queryAirports}
                    optionKey="code"
                    style={{ width: 300 }}
                  />
                )}
              </FormItem>
              <FormItem label="航班号" {...formItemLayout} required>
                {getFieldDecorator('flightNo', {
                  initialValue: service.flightNo,
                  normalize: (value) => {
                    return value ? value.toUpperCase() : '';
                  },
                  rules: [
                    { validator: this.checkCode }
                  ],
                  validateTrigger: 'onBlur'
                })(
                  <Input maxLength={6} minLength={5} disabled={true} style={{ width: 300 }}></Input>
                )}
              </FormItem>
              {
                isTime &&
                <FormItem label="航班日期" {...formItemLayout}>
                  {getFieldDecorator('flightDate', {
                    rules: [
                      { required: true, message: '请选择航班日期' },
                    ],
                  })(
                    <DatePicker format='YYYY-MM-DD' style={{ width: 300 }} />
                  )}
                </FormItem>
              }
              {
                !isTime &&
                <FormItem label="班期" {...formItemLayout}>
                  {getFieldDecorator('week', {
                    initialValue: service.periodList,
                    rules: [
                      {
                        required: true,
                        message: '请选择班期',
                      },
                    ],
                    validateTrigger: 'onBlur',
                  })(
                    <Select
                      mode="multiple"
                      style={{ width: 300 }}
                      placeholder="选择班期"
                    >
                      {this.week.map(item => (
                        <Option key={item.key}>{item.label}</Option>
                      ))}
                    </Select>
                  )}
                </FormItem>
              }
              <FormItem label="计划起飞时间" {...formItemLayout}>
                {getFieldDecorator('startTime', {
                  // initialValue: moment(service.startTime),
                  rules: [
                    { required: true, message: '请选择计划起飞时间' },
                  ],
                })(
                  <TimePicker format='HH:mm' disabledHours={this.disableStartHour} disabledMinutes={this.disableStartMinute} style={{ width: 300 }} />
                )}
              </FormItem>
              <FormItem label="计划到达时间" {...formItemLayout}>
                {getFieldDecorator('arriveTime', {
                  // initialValue: moment(service.arriveTime),
                  rules: [
                    { required: true, message: '请选择计划到达时间' },
                  ]
                })(
                  <TimePicker format='HH:mm' disabledHours={this.disableArriveHour} disabledMinutes={this.disableArriveMinute} style={{ width: 300 }} />
                )}
              </FormItem>
              <FormItem label="投放腹舱量" {...formItemLayout}>
                {getFieldDecorator('weight', {
                  normalize: (value, prevValue) => {
                    if (!value) return ''
                    return /^\d+$/.test(value) ? value : prevValue
                  },
                  // initialValue: service.weight,
                  rules: [
                    { required: true, message: '请输入投放腹舱量' },
                  ],
                })(
                  <Input maxLength={30} style={{ width: 300 }} addonAfter="kg"></Input>
                )}
              </FormItem>
              {
                !isTime &&
                <FormItem label="舱位生效日期" {...formItemLayout}>
                  {getFieldDecorator('effectStartDate', {
                    rules: [
                      { required: true, message: '请选择舱位生效日期' },
                    ],
                  })(
                    <DatePicker format='YYYY-MM-DD' disabledDate={this.disableStartDate} style={{ width: 300 }} />
                  )}
                </FormItem>
              }
              {
                !isTime &&
                <FormItem label="舱位失效日期" {...formItemLayout}>
                  {getFieldDecorator('effectEndDate', {
                    rules: [
                      { required: true, message: '请选择舱位失效日期' },
                    ],
                  })(
                    <DatePicker format='YYYY-MM-DD' disabledDate={this.disableEndDate} style={{ width: 300 }} />
                  )}
                </FormItem>
              }
              <FormItem label="货物类型" {...formItemLayout}>
                {getFieldDecorator('cargoTypeCodeList', {
                  initialValue: service.cargoTypeCodeList,
                  rules: [
                    { required: true, message: '请选择货物类型' },
                  ],
                  validateTrigger: 'onBlur'
                })(
                  <Select style={{ width: 300 }} mode="multiple">
                    {cargoTypes.map((cargoType, index) => (
                      <Option key={index} value={cargoType.code}>
                        {cargoType.name}
                      </Option>
                    ))}
                  </Select>
                )}
              </FormItem>
              {
                isTime && <>
                  <FormItem label="成本单价" {...formItemLayout}>
                    {getFieldDecorator('costUnitPrice', {
                      normalize: (value, prevValue) => {
                        if (!value) return ''
                        return /^\d+(\.\d{0,2})?$/.test(value) ? value : prevValue
                      },
                      initialValue: service.costUnitPrice,
                      rules: [
                        { required: true, message: '请输入销售单价' },
                      ],
                      validateTrigger: 'onBlur'
                    })(
                      <Input maxLength={30} style={{ width: 300 }} addonAfter="元/kg"></Input>
                    )}
                  </FormItem>
                  <FormItem label="销售单价" {...formItemLayout}>
                    {getFieldDecorator('saleUnitPrice', {
                      normalize: (value, prevValue) => {
                        if (!value) return ''
                        return /^\d+(\.\d{0,2})?$/.test(value) ? value : prevValue
                      },
                      initialValue: service.saleUnitPrice,
                      rules: [
                        { required: true, message: '请输入成本单价' },
                      ],
                      validateTrigger: 'onBlur'
                    })(
                      <Input maxLength={30} style={{ width: 300 }} addonAfter="元/kg"></Input>
                    )}
                  </FormItem>
                  <FormItem label="起订量" {...formItemLayout} required>
                    {getFieldDecorator('startWeight', {
                      normalize: (value, prevValue) => {
                        if (!value) return ''
                        return /^\d+$/.test(value) ? value : prevValue
                      },
                      initialValue: service.startWeight,
                      rules: [
                        { required: true, message: '请输入起订量' },
                      ],
                      validateTrigger: 'onBlur'
                    })(
                      <Input maxLength={30} style={{ width: 300 }} addonBefore="≥"></Input>
                    )}
                  </FormItem>
                  <FormItem label="单件重量限制" {...formItemLayout} required>
                    {getFieldDecorator('weightLimit', {
                      normalize: (value, prevValue) => {
                        if (!value) return ''
                        return /^\d+$/.test(value) ? value : prevValue
                      },
                      initialValue: service.weightLimit,
                      rules: [
                        { required: true, message: '请输入单件重量限制' },
                      ],
                      validateTrigger: 'onBlur'
                    })(
                      <Input maxLength={30} style={{ width: 300 }} addonBefore="≤"></Input>
                    )}
                  </FormItem>
                  <FormItem label='单件货物长' {...formItemLayout} required>
                    {getFieldDecorator('length', {
                      normalize: (value, prevValue) => {
                        if (!value) return ''
                        return /^\d+$/.test(value) ? value : prevValue
                      },
                      initialValue: service.length,
                      rules: [
                        { required: true, message: '请输入单件货物长' },
                      ],
                      validateTrigger: 'onBlur'
                    })(
                      <Input maxLength={30} style={{ width: 300 }}></Input>
                    )}
                  </FormItem>
                  <FormItem label='单件货物宽' {...formItemLayout} required>
                    {getFieldDecorator('width', {
                      normalize: (value, prevValue) => {
                        if (!value) return ''
                        return /^\d+$/.test(value) ? value : prevValue
                      },
                      initialValue: service.width,
                      rules: [
                        { required: true, message: '请输入单件货物宽' },
                      ],
                      validateTrigger: 'onBlur'
                    })(
                      <Input maxLength={30} style={{ width: 300 }}></Input>
                    )}
                  </FormItem>
                  <FormItem label='单件货物高' {...formItemLayout} required>
                    {getFieldDecorator('height', {
                      normalize: (value, prevValue) => {
                        if (!value) return ''
                        return /^\d+$/.test(value) ? value : prevValue
                      },
                      initialValue: service.height,
                      rules: [
                        { required: true, message: '请输入单件货物高' },
                      ],
                      validateTrigger: 'onBlur'
                    })(
                      <Input maxLength={30} style={{ width: 300 }}></Input>
                    )}
                  </FormItem>
                </>
              }
              <FormItem label="资源提供方" {...formItemLayout} required>
                {getFieldDecorator('supplierId', {
                  initialValue: {
                    key: service.supplierId,
                    label: `${service.supplierName}(${service.supplierCode})`
                  },
                  rules: [
                    { required: true, message: '请选择资源提供方' },
                  ],
                  validateTrigger: 'onBlur'
                })(
                  <ScrollSelect
                    allowClear
                    search={this.querySuppliers}
                    style={{ width: 300 }}
                    placeholder="请输入供应商名称或编码"
                    optionLabel="name"
                    optionKey="id"
                  />
                )}
              </FormItem>
              {
                isTime &&
                <FormItem label="服务商" {...formItemLayout} required>
                  {getFieldDecorator('operateSupplier', {
                    initialValue: service.operateSupplierCode ? {
                      key: service.operateSupplier,
                      label: `${service.operateSupplierName}(${service.operateSupplierCode})`
                    } : undefined,
                    rules: [
                      { required: true, message: '请选择服务商' },
                    ],
                    validateTrigger: 'onBlur'
                  })(
                    <ScrollSelect
                      allowClear
                      search={this.querySuppliers}
                      style={{ width: 300 }}
                      placeholder="请输入服务商名称或编码"
                      optionLabel="name"
                      optionKey="id"
                    />
                  )}
                </FormItem>
              }
              {isTime && <>
                <FormItem label="联系电话" {...formItemLayout}>
                  {getFieldDecorator('mobile', {
                    normalize: (value, prevValue) => {
                      if (!value) return ''
                      return /^\d+$/.test(value) ? value : prevValue
                    },
                    initialValue: service.mobile,
                    rules: [
                      { required: true, message: '请输入联系电话' },
                    ],
                    validateTrigger: 'onBlur'
                  })(
                    <Input maxLength={30} style={{ width: 300 }}></Input>
                  )}
                </FormItem>
                <FormItem label="收货时效要求" {...formItemLayout} required>
                  {getFieldDecorator('hours', {
                    normalize: (value, prevValue) => {
                      if (!value) return ''
                      return /^\d+$/.test(value) ? value : prevValue
                    },
                    initialValue: service.hours,
                    rules: [
                      { required: true, message: '请输入收货时效要求' },
                    ],
                    validateTrigger: 'onBlur'
                  })(
                    <Input maxLength={30} style={{ width: 300 }} addonAfter='小时'></Input>
                  )}
                </FormItem>
                <FormItem label="收货地址" {...formItemLayout} required>
                  {getFieldDecorator('address', {
                    initialValue: service.address,
                    normalize: (value, prevValue) => {
                      return value ? value.trim() : ''
                    },
                    rules: [
                      { required: true, message: '请输入收货地址' },
                    ],
                    validateTrigger: 'onBlur'
                  })(
                    <Input maxLength={30} style={{ width: 300 }}></Input>
                  )}
                </FormItem>
              </>
              }
              <Row>
                <Col offset={6} span={18}>
                  <Button style={{ marginRight: 12, width: 100 }} onClick={this.handleCancel}>取消</Button>
                  <Button type='primary' style={{ width: 100 }} onClick={this.handleSubmit}>提交</Button>
                </Col>
              </Row>
            </Col>
          </Row>
        </Card>
      </PageHeaderWrapper>
    )
  }
}

export default AirService
